package com.elepro.shoppingmall.service.comment;


import com.elepro.shoppingmall.entity.comments.Comment;
import com.elepro.shoppingmall.mapper.comment.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceIm implements CommentService{

    @Autowired
    private CommentMapper commentMapper;

    /**
     * 获取所有评论列表
     * @return
     */
    @Override
    public List<Comment> getCommentList() {

        return commentMapper.getCommentList();
    }

    /**
     * 获取评论所有列表并以json层次级别结构
     * @param goodsId
     * @return
     */
    @Override
    public List<Comment> selectCommentListByGoodsId(Long goodsId) {

        List<Comment> result = new ArrayList<>();

        List<Comment> commentListByGoodsId = commentMapper.selectCommentListByGoodsId(goodsId);

        for (Comment comment : commentListByGoodsId){
            List<Comment> commentList1 = new ArrayList<>();
            for (Comment comment1 : commentListByGoodsId){
                if (comment.getId()==comment1.getReplyCommentId())
                    commentList1.add(comment1);
            }
            comment.setCommentList(commentList1);

            if (comment.getReplyCommentId()==0){
                result.add(comment);
            }
        }

        return result;
    }

    /**
     * insert 评论
     * @param comment
     * @return
     */
    @Override
    public int insertComment(Comment comment) {

        if (comment.getReplyCommentId()==null||comment.getReplyUserId()==null){
            comment.setReplyCommentId(0l);
            comment.setReplyUserId(0l);
        }
        comment.setTime(new Date());
        commentMapper.insertComment(comment);

        return 0;
    }

    /**
     *删除评论根据id
     * @param id
     * @return
     */
    @Override
    public int deleteComment(Long id) {
        return commentMapper.deleteComment(id);
    }

    /**
     * 设置评论的图片url
     * @param comment
     * @param file
     * @return
     */
    public Comment setCommentPictureUrl(Comment comment, MultipartFile file){
        String fileName = file.getOriginalFilename();
        String dirPath = "D:/image/";

        File filePath = new File(dirPath);

        if (!filePath.exists()){
            filePath.mkdirs();
        }

        try {
            file.transferTo(new File(dirPath+fileName));
            comment.setPicture("http://localhost:8080/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return comment;
    }
}
